//
//  GameHomeViewController.swift
//  d11
//
//  Created by rhonin on 2018/11/15.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON

class GameHomeViewController: GameRootViewController,UITableViewDelegate,UITableViewDataSource ,FSPagerViewDelegate,FSPagerViewDataSource{
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return arrayBanner.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        pageControl.currentPage = index
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        let model = arrayBanner[index]
        cell.imageView?.set_kf_Images(urlString: model.picturePath, placeHolder: "banner_placeholder")
         cell.layer.cornerRadius = 10
         cell.clipsToBounds = true
   //     cell.imageView?.clipsToBounds = true
     //   cell.textLabel?.text = ...
        return cell
    }
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        let vc = GameDetailController()
        let model = arrayBanner[index]
        vc.url = model.url
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    var arrayMath = [GameMatchModel]()
    var arrayNews = [GameNewsModel]()
    var arrayBanner = [GameBannerModel]()
    var totolNum = 0
    
    var pageNume : NSInteger = 1{
        willSet{
            if newValue < 1 {
                self.pageNume = 1
            }
        }
      
    }
    
    lazy var pageView: FSPagerView = {

        let pg = FSPagerView(frame: CGRect(x: 0, y: 40, width: ScreenWidth, height:   (ScreenWidth-42)*173/333))
        pg.isInfinite = true
        pg.itemSize = CGSize(width: ScreenWidth-42, height: (ScreenWidth-42)*173/333)
     
        pg.dataSource = self
        pg.isInfinite = true
        pg.automaticSlidingInterval = 3.0
        pg.transformer = FSPagerViewTransformer(type: .linear)
    
        pg.delegate = self
        pg.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
       
        return pg
    }()
    let pageControl = FSPageControl()
    lazy var matchButonOne: MatchButton = {
        let but = MatchButton(frame: CGRect(x: 21, y: self.secondView.bottomY, width: (ScreenWidth-54)/2, height: 60))
         but.tag = 0
        let gest =  UITapGestureRecognizer(target: self, action: #selector(gotoMatch(tag:)))
        but.addGestureRecognizer(gest)
        return but
    }()
    lazy var matchButonTwo: MatchButton = {
        let but = MatchButton(frame: CGRect(x: 21+12+(ScreenWidth-54)/2, y: self.secondView.bottomY, width: (ScreenWidth-54)/2, height: 60))
        but.tag = 1
        let gest =  UITapGestureRecognizer(target: self, action: #selector(gotoMatch(tag:)))
        but.addGestureRecognizer(gest)
        return but
    }()
    lazy var matchButonThree: MatchButton = {
        let but = MatchButton(frame: CGRect(x: 21, y: self.secondView.bottomY+60+9, width: (ScreenWidth-54)/2, height: 60))
        let gest =  UITapGestureRecognizer(target: self, action: #selector(gotoMatch(tag:)))
        but.addGestureRecognizer(gest)
        but.tag = 2
        return but
    }()
    lazy var matchButonFour: MatchButton = {
        let but = MatchButton(frame: CGRect(x: 21+12+(ScreenWidth-54)/2, y: self.secondView.bottomY+60+9, width: (ScreenWidth-54)/2, height: 60))
         but.tag = 3
        let gest =  UITapGestureRecognizer(target: self, action: #selector(gotoMatch(tag:)))
        but.addGestureRecognizer(gest)
        return but
    }()
    var labHead : UILabel?
    
    lazy var secondView: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: self.pageView.bottomY+18, width: ScreenWidth, height: 25))
        let viewY = UIView(frame: CGRect(x: 21, y: 5, width: 1, height: 10))
        viewY.backgroundColor = RGBAlpa(17,17,17,1)
        v.addSubview(viewY)
        let lab = UILabel(frame: CGRect(x: 23+8, y: 2, width: 200, height: 16))
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textColor = RGBAlpa(17,17,17,1)
        self.labHead = lab
        v.addSubview(lab)
    
        return v
    }()
   
   
    lazy var table: UITableView = {
        let tab = UITableView(frame: .zero, style: UITableView.Style.grouped)
        tab.delegate = self
        tab.dataSource = self
        tab.backgroundColor = RGBAlpa(220,219,219,1)
        tab.estimatedRowHeight = 138;
        tab.rowHeight = UITableView.automaticDimension;
        if  #available(iOS 11.0, *){
            tab.contentInsetAdjustmentBehavior = .never
        }
        tab.register( UINib.init(nibName: "GmHomeTableListCell", bundle: nil), forCellReuseIdentifier: "gmhomeCell")
        return tab
    }()
   
    lazy var headView: UIView = {
        let head = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 1))
        let  height = 1
        let imageHead = UIImageView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 117))
        imageHead.image = UIImage(named: "bg-top-game")
        head.backgroundColor = RGBAlpa(227,228,231,1)
        head.addSubview(imageHead)
        head.addSubview(self.pageView)
        head.addSubview(self.secondView)
        head.addSubview(self.matchButonOne)
        head.addSubview(self.matchButonTwo)
        head.addSubview(self.matchButonThree)
        head.addSubview(self.matchButonFour)
        head.height = self.matchButonFour.bottomY+12
        return head
    }()
    var balanceButton: UIButton?
    override func viewDidLoad() {
        super.viewDidLoad()
     
       
        pageControl.frame = CGRect(x: 0, y: pageView.bottomY-20, width: 10, height: 20)
        pageControl.centerX = ScreenWidth/2
        headView.addSubview(pageControl)
      
        let topLogo = UIImage(named: "icon_nav_left_logo")
        let titleView = UIView()
        let topLogoView = UIImageView(image: topLogo)
        titleView.addSubview(topLogoView)
        topLogoView.contentMode = .scaleToFill
        topLogoView.frame = CGRect(x: -(137/2), y:-(35/2), width: 137, height: 35)
        navigationItem.titleView = titleView
        
        let balanceButton = UIButton(type: .custom)
        balanceButton.setTitle("Fetchin", for: .normal)
        balanceButton.setImage(UIImage(named: "icon_nav_right_amount"), for: .normal)
        balanceButton.setTitleColor(UIColor.white, for: .normal)
        balanceButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -12, bottom: 0, right: 0)
        balanceButton.titleLabel?.font = UIFont(name: balanceButton.titleLabel!.font.fontName, size: 14)
        self.balanceButton = balanceButton
        
        let barItem = UIBarButtonItem(customView: balanceButton)
    
        self.navigationItem.setRightBarButton(barItem, animated: true)

        balanceButton.addTarget(self, action: #selector(self.pushWebViewTransfer), for: .touchUpInside)
        self.firstreload()
          self.performRefresh(withData: GlobalInfo.memberInfoData!, withHallData: GlobalInfo.hallInfoData!, true)
    }
    
    func firstreload()  {
        view.addSubview(loadingView)
        weak var this = self
        MCNetworking.shareInstance.request(requestType: .GET, encoding: .JSON, serve: .normal, param: nil, headerCustom: nil, urlString: listForAndroid+"/\(pageNume)", complete: { (data) in
            let json = (data as! JSON)["result"].arrayValue
            for item in json{
                if item["sportInfo"].exists(){
                    let itemin = item["sportInfo"].arrayValue
                    for itemtmp in itemin{
                        let model = GameMatchModel().getValueWithJson(dic: itemtmp)
                        this?.arrayMath.append(model)
                    }
                }
                if item["newInfo"].exists(){
                    let itemin = item["newInfo"]["contentDOs"].arrayValue
                    for itemtmp in itemin{
                        let model = GameNewsModel().getValueWithJson(dic: itemtmp)
                        this?.arrayNews.append(model)
                    }
                    this?.totolNum = item["newInfo"]["total"].intValue
                }
                if item["imglinks"].exists(){
                    let itemin = item["imglinks"].arrayValue
                    for itemtmp in itemin{
                        let model = GameBannerModel().getValueWithJson(dic: itemtmp)
                        this?.arrayBanner.append(model)
                    }
                }
            }
            this?.pageControl.numberOfPages = (this?.arrayBanner.count)!
            this?.loadingView.removeFromSuperview()
            this?.inituI()
            this?.reloadUI()
        }, fail: { (data) in
            this?.loadingView.removeFromSuperview()
            MBProgressHUD.showMessage("服务器异常", to: this!.view)
            this?.inituFail()
        }, requestProgress: nil)
    }
    func inituFail() {
       self.failBtn.center = self.view.center
        self.view.insertSubview(self.failBtn, at: 0)
    }
    override func failreload() {
        self.failBtn.removeFromSuperview()
        self.firstreload()
    }
    override func viewWillAppear(_ animated: Bool) {
        weak var this  = self
        //api2.0接口开始
        NetWorkRequest(API.memberInfoUL(url: "face82b", ccToken: API.getCcToken(), vcToken: API.getVcToken()), completion:  { (responseData,statusCode,strData) -> (Void) in
            if(statusCode == 200){
                //取出data的数据并转化为字典数据
                let dataDict = responseData["data"].dictionaryObject
                //获取到状态值
                let statusStringJson = responseData["status"]
                //把状态值的字符串转为int值
                let statusString = Int("\(statusStringJson)")
                //获取到传递过来的msg
                let msgStringJson = responseData["msg"]
                //把msgStringJson转为字符串
                let msgString = "\(msgStringJson)"
                //判断是否相等的
                if(statusString == 0){
                    let memberInfoArray = dataDict?["response"] as? [String:Any] ?? [:]
                    GlobalInfo.memberInfoData = memberInfoArray
                    print("用户信息: \(memberInfoArray),\(String(describing: GlobalInfo.memberInfoData))")
                    DispatchQueue.main.async {
                        GlobalInfo.memberInfoData = memberInfoArray
                        this?.performRefresh(withData: GlobalInfo.memberInfoData!, withHallData: GlobalInfo.hallInfoData!, true)
                    }
                }else{
                    DispatchQueue.main.async {
                        //弹出报错后的问题
                        UIHelper.alertSimpleMessage(about: msgString, withDescription: "", in: self)
                    }
                }
                
            }else{
                DispatchQueue.main.async {
                    //弹出报错后的问题
                    UIHelper.alertSimpleMessage(about: "获取用户信息失败!", withDescription: "", in: self)
                }
            }
        },failed: {(faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
            
        }){() -> (Void) in
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "网络请求异常,获取用户信息失败。", withDescription: "", in: self)
                
            }
        }
        
        //api2.0接口结束
    
//        RequestHelper.get(atPath: "/clientsAPIs/memberInfoUL", withCompletion: { data in
//            let memberInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
//            DispatchQueue.main.async {
//                GlobalInfo.memberInfoData = memberInfoArray
//                this?.performRefresh(withData: GlobalInfo.memberInfoData!, withHallData: GlobalInfo.hallInfoData!, true)
//            }
//        },withError: { error in
//             UIHelper.alertSimpleMessage(about: "服务器异常,获取用户信息失败。\(getErrorString())", withDescription: "", in: self)
//        })
    }
    
    func reloadUI() {
       
        self.pageView.reloadData()
       
        self.table.reloadData()
        for i in 0 ..< arrayMath.count {
            
            if i == 0 {
                   labHead?.text = arrayMath[0].superTitle
                  self.matchButonOne.fillCell(dic: arrayMath[0])
            }else if i == 1{
                self.matchButonTwo.fillCell(dic: arrayMath[1])
            }else if i == 2{
                 self.matchButonThree.fillCell(dic: arrayMath[2])
            }else if i == 3{
                self.matchButonFour.fillCell(dic: arrayMath[3])
            }
        }
      
    }
    @objc  func gotoMatch(tag:UITapGestureRecognizer)  {
        if arrayMath.count > tag.view!.tag {
            let vc = GameDetailController()
            vc.content = arrayMath[tag.view!.tag].content
            vc.title = "赛事分析"
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    func performRefresh(withData: [String:Any], withHallData: [[String:Any]] , _ isInit: Bool = false){
        //self.memberInfoData = withData
        
        if let balanceStr = withData["balance"] as? String {
            //判断登陆状态
            self.refreshBalance(withBalance: Double(balanceStr))
        }
    }
    
    func refreshBalance(withBalance: Double?){
        
        if UserHelper.getLoginStatus() {
            //             UserDefaults.standard.set(withBalance, forKey: "mtwithBalance")
            if let balance = withBalance {
                
                self.balanceButton?.setTitle(String(format: "%.2f", balance), for: .normal)
                
                let size = balanceButton!.intrinsicContentSize
                //balanceButton!.frame = CGRect(x: balanceButton!.frame.origin.x, y: balanceButton!.frame.origin.y, width: size.width, height: 33)
                //balanceButton!.frame.origin = CGPoint(x: balanceButton!.frame.origin.x, y: -33)
                balanceButton!.frame.size = CGSize(width: size.width, height: 33)
            }
        }else{
            let button1 = UIBarButtonItem(title: "注册/登录", style: .plain, target: self, action: #selector(self.loginRegisterButtonClick))
            button1.tintColor = HexRGBAlpha(0xFBBC64,1)
            
            self.navigationItem.setRightBarButtonItems([button1], animated: false)
        }
    }
    
    
    
    /**** View Actions ****/
    @objc func loginRegisterButtonClick(){
        setRootLoginVC()
        // GlobalInfo.mainTabBarController?.navigationController?.popToRootViewController(animated: true)
        //        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func pushWebViewTransfer(){
        if  GlobalInfo.isPlatformMainhtml == nil || GlobalInfo.isPlatformMainhtml != false{
            self.navigateWebView(toPath: "/walletm/transfer", "",sign: true)
        }else{
            let vc = MainAccountVC()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    /**** Others ****/
    //mt  2018.6.4 由https改为http
    func navigateWebView(toPath: String, _ title: String,sign:Bool){
        let goNext:WebViewController = WebViewController.init()
           
        let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + toPath
        goNext.url = url
        goNext.title = title
        goNext.signLoging=sign
        self.navigationController?.pushViewController(goNext, animated: true)
    }
    func inituI() {
        view.addSubview(table)
        self.table.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
        }
        self.table.tableHeaderView = headView
        weak var this = self
       
        self.table.mj_header =  MJRefreshNormalHeader {
            this?.pageNume = 1
            
            this?.arrayNews.removeAll()
            if this!.totolNum <= this!.arrayNews.count{
               // this?.table.mj_footer.endRefreshingWithNoMoreData()
            }else{
                this?.table.mj_footer?.resetNoMoreData()
            }
            this?.refresh()
        }
        let footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            this?.pageNume += 1
            this?.refresh()
        })
        self.table.mj_footer = footer
        footer.setTitle("没有更多内容了", for: .noMoreData)
    }
    
    func refresh()  {
        weak var this  = self
        MCNetworking.shareInstance.request(requestType: .GET, encoding: .JSON, serve: .normal, param: nil, headerCustom: nil, urlString: listForAndroid+("/\(pageNume)"), complete: { (data) in
            this?.arrayMath.removeAll()
            
            this?.arrayBanner.removeAll()
            let json = (data as! JSON)["result"].arrayValue
            
            for item in json{
                if item["sportInfo"].exists(){
                    let itemin = item["sportInfo"].arrayValue
                    for itemtmp in itemin{
                        let model = GameMatchModel().getValueWithJson(dic: itemtmp)
                        this?.arrayMath.append(model)
                    }
                }
                if item["newInfo"].exists(){
                    let itemin = item["newInfo"]["contentDOs"].arrayValue
                    for itemtmp in itemin{
                        let model = GameNewsModel().getValueWithJson(dic: itemtmp)
                        this?.arrayNews.append(model)
                    }
                    
                     this?.totolNum = item["newInfo"]["total"].intValue
                }
                if item["imglinks"].exists(){
                    let itemin = item["imglinks"].arrayValue
                    for itemtmp in itemin{
                        let model = GameBannerModel().getValueWithJson(dic: itemtmp)
                        this?.arrayBanner.append(model)
                    }
                }
            }
            this?.pageControl.numberOfPages = (this?.arrayBanner.count)!
            this?.reloadUI()
            this?.table.mj_header?.endRefreshing()
            if this!.totolNum <= this!.arrayNews.count{
                this?.table.mj_footer?.endRefreshingWithNoMoreData()
            }else{
                this?.table.mj_footer?.endRefreshing()
            }
        }, fail: { (data) in
            MBProgressHUD.showMessage(data, to: this!.view)
        }, requestProgress: nil)
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 42))
        let viewY = UIView(frame: CGRect(x: 21, y: 12, width: 1, height: 10))
        viewY.backgroundColor = RGBAlpa(17,17,17,1)
        v.addSubview(viewY)
        if arrayNews.count > 0 {
            let leftmodel = arrayNews[0]
            let lab = UILabel(frame: CGRect(x: 31, y: 9, width: 200, height: 16))
            lab.font = UIFont.systemFont(ofSize: 14)
            
            lab.text = leftmodel.superTitle
            lab.textColor = RGBAlpa(17,17,17,1)
            v.addSubview(lab)
        }
      
        return v
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayNews.count/2+arrayNews.count%2
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = table.dequeueReusableCell(withIdentifier: "gmhomeCell")
        let leftmodel = arrayNews[indexPath.row*2]
        var rightModel:GameNewsModel?
        if indexPath.row*2+1 < arrayNews.count{
            rightModel = arrayNews[indexPath.row*2+1]
        }
        weak var this = self
        (cell as! GmHomeTableListCell).configslef(leftModel: leftmodel, rightModel: rightModel)
        (cell as! GmHomeTableListCell).viewClick = { (typeclick,model) in
            if typeclick == viewClickType.left{
                
            }else{
                
            }
            let cont = GameDetailController()
            cont.content = model?.content
            cont.hidesBottomBarWhenPushed = true
            this?.navigationController?.pushViewController(cont, animated: true)
        }
        return cell!
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}


class MatchButton: UIView {
    let imageOne = UIImageView()
    let imageTwo = UIImageView()
    let labOne = UILabel(frame: .zero)
    let labTwo = UILabel(frame: .zero)
    let labBotton = UILabel(frame: .zero)
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initUI()
        self.addmas()
    }
    func addmas() {

        imageOne.clipsToBounds = true
//        imageOne.backgroundColor = UIColor.red
        imageOne.contentMode = .scaleAspectFill
        imageTwo.clipsToBounds = true
//        imageTwo.backgroundColor = UIColor.yellow
        imageTwo.contentMode = .scaleAspectFill
        self.imageOne.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 20, height: 25))
            make.centerX.equalTo(self.width/5)
            make.top.equalTo(8)
        }
        self.imageTwo.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 20, height: 25))
            make.centerX.equalTo(self.width*4/5)
            make.top.equalTo(8)
        }
        self.labOne.snp.makeConstraints { (make) in
            make.top.equalTo(imageOne.snp.bottom)
            make.centerX.equalTo(imageOne.snp.centerX)
        }
        self.labTwo.snp.makeConstraints { (make) in
            make.top.equalTo(imageTwo.snp.bottom)
            make.centerX.equalTo(imageTwo.snp.centerX)
        }
       
    }
    func fillCell(dic:GameMatchModel)  {
        labOne.text = dic.teamAName
        labTwo.text = dic.teamBName
        labBotton.text = dic.title
        imageOne.set_kf_Images(urlString: dic.aphoto, placeHolder: "logo_placehoder")
        imageTwo.set_kf_Images(urlString: dic.bphoto, placeHolder: "logo_placehoder")
    }
    func initUI() {
        let image = UIImageView(frame: CGRect(x: 0, y: 0, width: self.width, height: 50))
        image.contentMode = .scaleAspectFill
        image.image = UIImage(named: "bg-team")
        image.clipsToBounds = true
        self.addSubview(image)
        
        let imageBotton = UIImageView(frame: CGRect(x: 0, y: 50, width: self.width, height: 13))
         imageBotton.contentMode = .scaleAspectFill
        imageBotton.image = UIImage(named: "bg-macth")
          imageBotton.clipsToBounds = true
       // imageBotton.
        self.addSubview(imageBotton)
        self.addSubview(imageOne)
        self.addSubview(imageTwo)
        labOne.font = UIFont.systemFont(ofSize: 9)
        labTwo.font = UIFont.systemFont(ofSize: 9)
        self.addSubview(labOne)
        self.addSubview(labTwo)
        self.addSubview(labBotton)
        labBotton.font = UIFont.systemFont(ofSize: 8)
        labBotton.textColor = UIColor.white
        labBotton.textAlignment = .center
        self.labBotton.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.width.equalTo(self.width)
            make.top.equalTo(50)
            make.height.equalTo(13)
        }
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
